import tools from '../utils/tools'
import CryptoJS from '../utils/crypto-js/index'

export default class mockBridge {
    constructor() {
        this.platform = 'mock'
        this._readyPromise = Promise.resolve()
    }

    onReady() {
        return this._readyPromise
    }

    back(params) {
        history.back()
    }

    navigateTo(params) {
        if (this.getUserInfo().uid) {
            uni.navigateTo(params)
        } else {
            console.log('navigateTo', params)
        }
    }

    redirectTo(params) {
        if (this.getUserInfo().uid) {
            uni.redirectTo(params)
        } else {
            console.log('redirectTo', params)
        }
    }

    reLaunch(params) {
        if (this.getUserInfo().uid) {
            uni.reLaunch(params)
        } else {
            console.log('reLaunch', params)
        }
    }

    // 更新分享信息
    updateShareData(params) {
        console.log(params)
        uni.webView.postMessage({
            data: {
                type: 'updateShareData',
                ...params
            }
        });
    }

    // 长按调起保存
    downloadUrl(params) {
        uni.webView.postMessage({
            data: {
                type: 'downloadUrl',
                platform: params.platform
            }
        });
    }

    preview(params) {
        uni.webView.postMessage({
            data: {
                type: 'preview',
                params: params.urls
            }
        });
    }

    // 打开一个新的专题页面
    goZhuanti(url) {
        location.href = url
    }

    // 更新页面标题
    setTitle(title) {
        document.title = title
    }

    getUserInfo() {
        if (this.userInfo) return this.userInfo
        try {
            let u = decodeURIComponent(tools.getRouteQuery().u || '')
            if (!u) return {}
            const plainText = CryptoJS.AES.decrypt(u, 'xkafrontendgroup')
            this.userInfo = JSON.parse(plainText.toString(CryptoJS.enc.Utf8))
            return this.userInfo
        } catch (e) {
            return {
                uid: ''
            }
        }
    }
}
